package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class SearchingForFilesByName {
	public static void main(String[] args) throws Exception {
		Path searchFile = Paths.get("1.jpg");
		Search walk = new Search(searchFile);
		EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

		Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
		for (Path root : dirs) {
			if (!walk.found) {
				Files.walkFileTree(root, opts, Integer.MAX_VALUE, walk);
			}
		}

		if (!walk.found) {
			System.out.println("文件 " + searchFile + " 未搜索到!");
		}

	}
}

class Search implements FileVisitor {

	private final Path searchedFile;
	boolean found;

	Search(Path searchedFile) {
		this.searchedFile = searchedFile;
		this.found = false;
	}

	private void search(Path file) throws IOException {
		Path name = file.getFileName();
		if (name != null && name.equals(searchedFile)) {
			System.out.println("搜索文件找到: " + searchedFile + " 在 "
					+ file.toRealPath().toString());
			found = true;
		}
	}

	@Override
	public FileVisitResult postVisitDirectory(Object dir, IOException exc) {
		System.out.println("访问: " + dir);
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) {
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
		search((Path) file);
		if (!found) {
			return FileVisitResult.CONTINUE;
		} else {
			return FileVisitResult.TERMINATE;
		}
	}

	@Override
	public FileVisitResult visitFileFailed(Object file, IOException exc) {
		return FileVisitResult.CONTINUE;
	}
}

